// code by onemen
var TMP_Places =
{
   _pref: null,
   init : function ()
   {
      if (!this._pref)
         this._pref = Components.classes["@mozilla.org/preferences-service;1"]
                                 .getService(Components.interfaces.nsIPrefBranch);

      PlacesController.openLinksInTabs = this.openLinksInTabs;
      PlacesController._openBrowserWith = this._openBrowserWith;

      eval("PlacesController.buildContextMenu ="+PlacesController.buildContextMenu.toString().replace(
         'return true;',
         'TMP_Places.buildContextMenu(popup); \ $&'
      ));

      eval("PlacesController.mouseLoadURI ="+PlacesController.mouseLoadURI.toString().replace(
         'openUILink(node.uri, event, false, false);',
         'TMP_Places.openUILink(node.uri, event, false, false);'
      ));

      eval("PlacesController.openLinkInNewTab ="+PlacesController.openLinkInNewTab.toString().replace(
         'openNewTabWith(node.uri, null, null);',
         'TMP_Places.openNewTabWith(node.uri, "tab");'
      ));

      eval("PlacesController.openLinkInCurrentWindow ="+PlacesController.openLinkInCurrentWindow.toString().replace(
         'loadURI(node.uri, null, null, false);',
         'TMP_Places.openLinkInCurrent(node.uri);'
      ));

      eval("PlacesController.showAddBookmarkUI ="+PlacesController.showAddBookmarkUI.toString().replace(
         'this._showBookmarkDialog("add", uri, title);',
         'title = TMP_Places.getFixTitle(uri, title); \ $&'
      ));

      if ("BookmarksEventHandler" in window)
      eval("BookmarksEventHandler.onClick ="+BookmarksEventHandler.onClick.toString().replace(
         'PlacesController.openLinksInTabs();',
         'var v = PlacesController.activeView;\
          if (v.hasSingleSelection && PlacesController.nodeIsURI(v.selectedNode))\
            PlacesController.mouseLoadURI(event);\
          else if (PlacesController.nodeIsContainer(v.selectedNode))\
            PlacesController.openLinksInTabs();'
      ));

      window.removeEventListener('load', function () { TMP_Places.init(); }, false);
   },

   buildContextMenu : function (popup)
   {
      var where = TMP_whereToOpen("extensions.tabmix.opentabfor.bookmarks");
      var singlemode = this._pref.getBoolPref("extensions.tabmix.singleWindow");
      var browserWindow = PlacesController._getBrowserWindow();

      var _open = popup.childNodes[0];
      var _openInWindow = popup.childNodes[2];
      var _openInTab = popup.childNodes[3];

      if (browserWindow) {
         if (!_openInWindow.hidden && singlemode)
            _openInWindow.hidden = true;
         else if (_openInWindow.hasAttribute("default"))
           _openInWindow.removeAttribute("default");
         _openInTab.setAttribute("default", where.inNew);
         if (where.lock)
            _open.hidden = true;
         else
            _open.setAttribute("default", !where.inNew);
      }
      else {
         _open.hidden = true;
         _openInTab.hidden = true;
         _openInWindow.hidden = false;
         _openInWindow.setAttribute("default", true);
      }
   },

   historyMenu : function (event)
   {
      var url = event.target.getAttribute('statustext');
      if (url)
         this.openUILink(url, event, false, true);
   },

   openUILink: function PC_TMP_openUILink(url, e, ignoreButton, ignoreAlt)
   {
      var where = this.whereToOpenLink(url, e, ignoreButton, ignoreAlt);

      if (where == "tab" || where == "tabshifted")
         this.openNewTabWith(url, where);
      else
         openUILinkIn(url, where, false, null);
   },

   // this function based on openNewTabWith from contentAreaUtils.js
   openNewTabWith : function PC_TMP_openNewTabWith(url, where)
   {
      var loadInBackground = getBoolPref("browser.tabs.loadBookmarksInBackground", false);
      if (where == "tabshifted")
         loadInBackground = !loadInBackground;

      var wintype = document.documentElement.getAttribute('windowtype');
      var originCharset;
      if (wintype == "navigator:browser") {
         originCharset = window.content.document.characterSet;
         window.content.focus();
      }

      var browser = getTopWin().document.getElementById("content");
      browser.loadOneTab(url, null, originCharset, null, loadInBackground, false);
   },

   openLinkInCurrent : function PC_TMP_openLinkInCurrent(url)
   {
      if (this.whereToOpenLink(url) == "current")
         loadURI(url, null, null, false);
      else
         this.openNewTabWith(url, "tab");
   },

   isBookmarklet : function (url)
   {
      var jsURL = /^ *javascript:/;
      return jsURL.test(url) ? true : false;
   },

   whereToOpenLink : function (url, e, ignoreButton, ignoreAlt)
   {
      // open bookmarklet in current tab
      if (this.isBookmarklet(url))
         return "current";

      var where = whereToOpenLink(e, ignoreButton, ignoreAlt);

      var browser = getTopWin().document.getElementById("content");
      var aTab = browser.mCurrentTab;

//      if ((this._pref.getBoolPref(prefStringTMBookmark) || aTab.hasAttribute("locked"))
//           && !openInWebPanelTM(node, aDS))
      if ((this._pref.getBoolPref(prefStringTMBookmark) || aTab.hasAttribute("locked")))
         if (e && this._pref.getBoolPref(prefStringTMUseMiddleClick) &&
               (e.button == 1 || e.button == 0 && (e.ctrlKey || e.metaKey)))
            where = "current";
         else if (where == "current"
               && !( browser.isBlankTab(aTab) && !aTab.hasAttribute("busy") ))
            where = "tab";

      return where;
   },

   openLinksInTabs: function TMP_PC_openLinksInTabs() {
      var bmGroup = [], isFolder;
      var node = this._activeView.selectedNode;
      if (this._activeView.hasSingleSelection && this.nodeIsFolder(node)) {
         isFolder = true;
         asFolder(node);
         var wasOpen = node.containerOpen;
         node.containerOpen = true;
         var cc = node.childCount;
         for (var i = 0; i < cc; ++i) {
            var childNode = node.getChild(i);
            if (this.nodeIsURI(childNode))
               bmGroup.push(childNode.uri);
         }
         node.containerOpen = wasOpen;
      }
      else {
         isFolder = false;
         var nodes = this._activeView.getSelectionNodes();
         for (i = 0; i < nodes.length; ++i) {
            if (this.nodeIsURI(nodes[i]))
               bmGroup.push(nodes[i].uri);
         }
      }

      // If the bookmark group was completely invalid, just bail.
      if (bmGroup.length != 0) {
         if (!this._confirmOpenTabs(bmGroup.length))
            return;

         var browserWindow = this._getBrowserWindow();

         if (browserWindow)
            browserWindow.TMP_Bookmark.openGroup(bmGroup, "tab", isFolder);
         else {
            var win = openDialog("chrome://browser/content/browser.xul", "_blank",
                        "chrome,all,dialog=no", bmGroup.join("|"));
            win.openFromPlaces = true;
         }
      }

   },

   _openBrowserWith: function TMP_PC__openBrowserWith(url) {
     var win = openDialog("chrome://browser/content/browser.xul", "_blank",
                "chrome,all,dialog=no", url, null, null);
     win.openFromPlaces = true;
   },

   _getBookmarkTitle : function (url)
   {
      var _uri = PlacesController._uri(url);
      if (PlacesController.bookmarks.isBookmarked(_uri))
         return PlacesController.bookmarks.getItemTitle(_uri);

      return null;
   },

   // start showAddBookmarkUI with user defined title if exist
   getFixTitle : function (url, title)
   {
      var browser = PlacesController._getBrowserWindow().getBrowser();
      if (browser.mCurrentBrowser.currentURI == url &&
               browser.mCurrentTab.getAttribute('label-uri') == url.spec)
         title = browser.mCurrentTab.getAttribute('fixed-label');

      return title;
   }

}
